package com.woniu.springsecurity.entity;

import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

@Data
public class User implements UserDetails {
    private Integer id;
    private String username;
    private String password;
    //用户关联的角色列表, 角色中包含权限
    private List<Role> roleList;

    // 用户拥有的权限列表,? extends GrantedAuthority ?表示泛型只能是GrantedAuthority的子类
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        //封装数据
        for (Role role : roleList) {
            list.add(new SimpleGrantedAuthority(role.getName()));
            // 权限
            for (Perms permission : role.getPermsList()) {
                list.add(new SimpleGrantedAuthority(permission.getName()));
            }
        }
        return list;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    // 账户是否未过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    // 账户是否未锁定
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    // 密码是否未过期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    // 账户是否可用
    @Override
    public boolean isEnabled() {
        return true;
    }
}
